# 删除过期10天的文件夹和文件
# 设置要清理的目录路径
$targetPath = "D:\Backups"  # 请修改为您需要清理的目录路径

# 设置日志文件路径
$logFile = "C:\Logs\cleanup_$(Get-Date -Format 'yyyyMMdd').log"

# 创建日志目录(如果不存在)
$logDir = Split-Path -Path $logFile -Parent
if (-not (Test-Path -Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}

# 记录日志函数
function Write-Log {
    param (
        [string]$message
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$timestamp - $message" | Out-File -FilePath $logFile -Append
    Write-Host "$timestamp - $message"
}

# 检查目标目录是否存在
if (-not (Test-Path -Path $targetPath)) {
    Write-Log "错误: 目标目录 $targetPath 不存在"
    exit 1
}

# 计算10天前的日期
$cutoffDate = (Get-Date).AddDays(-10)

Write-Log "开始清理 $targetPath 中超过10天的文件和文件夹"

# 获取所有文件和文件夹
$items = Get-ChildItem -Path $targetPath -Recurse

# 统计变量
$deletedFiles = 0
$deletedFolders = 0
$totalSize = 0

# 先处理文件
$files = $items | Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt $cutoffDate }
foreach ($file in $files) {
    try {
        $fileSize = $file.Length
        $totalSize += $fileSize
        $fileSizeMB = [math]::Round($fileSize / 1MB, 2)
        
        Write-Log "删除文件: $($file.FullName) (大小: $fileSizeMB MB, 修改时间: $($file.LastWriteTime))"
        Remove-Item -Path $file.FullName -Force
        $deletedFiles++
    }
    catch {
        Write-Log "删除文件失败: $($file.FullName) - $($_.Exception.Message)"
    }
}

# 然后处理文件夹 (从最深层开始，避免删除非空文件夹的错误)
$folders = $items | Where-Object { $_.PSIsContainer -and $_.LastWriteTime -lt $cutoffDate } | Sort-Object -Property FullName -Descending

foreach ($folder in $folders) {
    # 检查文件夹是否为空
    $folderItems = Get-ChildItem -Path $folder.FullName -Force -ErrorAction SilentlyContinue
    if ($folderItems.Count -eq 0) {
        try {
            Write-Log "删除文件夹: $($folder.FullName) (修改时间: $($folder.LastWriteTime))"
            Remove-Item -Path $folder.FullName -Force -Recurse
            $deletedFolders++
        }
        catch {
            Write-Log "删除文件夹失败: $($folder.FullName) - $($_.Exception.Message)"
        }
    }
    else {
        Write-Log "跳过非空文件夹: $($folder.FullName)"
    }
}

# 转换总大小为易读格式
$totalSizeMB = [math]::Round($totalSize / 1MB, 2)
$totalSizeGB = [math]::Round($totalSize / 1GB, 2)

# 输出统计信息
Write-Log "清理完成. 删除了 $deletedFiles 个文件和 $deletedFolders 个文件夹"
Write-Log "释放空间: $totalSizeMB MB ($totalSizeGB GB)"
Write-Log "详细信息请查看日志文件: $logFile"